let PreloadConfig = require('./PreloadConfig');


function preload(progressCallback, completedCallback) {
  if (PreloadConfig.files.length === 0 && PreloadConfig.directories.length === 0) {
    completedCallback([], []);
    return;
  }
  
  let stepCount = {};
  
  function preloadStep(path) {
    
    stepCount[path] = {
      totalCount: 0,
      completedCount: 0,
      isCompleted: false,
    };
    
    function onProgress(completedCount, totalCount) {
      if (stepCount[path] === undefined) {
        stepCount[path] = {
          totalCount,
          completedCount,
          isCompleted: false,
        };
      } else {
        stepCount[path].totalCount = totalCount;
        stepCount[path].completedCount = Math.min(totalCount, completedCount);
      }
      
      // cc.log("progressCallback", path, stepCount[path].completedCount, stepCount[path].totalCount);
      if (progressCallback) {
        let total = 0;
        let completed = 0;
        let keys = Object.keys(stepCount);
        for (let i = 0; i < keys.length; i++) {
          let key = keys[i];
          total += stepCount[key].totalCount;
          completed += stepCount[key].completedCount;
        }
        
        progressCallback(completed, total);
      }
    }
    
    function onCompleted(errors, items) {
      stepCount[path].isCompleted = true;
      stepCount[path].errors = errors;
      stepCount[path].items = items;
      if (errors && errors.length) {
        stepCount[path].totalCount -= errors.length;
      }
      
      if (completedCallback) {
        let allCompleted = true;
        let keys = Object.keys(stepCount);
        for (let i = 0; i < keys.length; i++) {
          let key = keys[i];
          if (!stepCount[key].isCompleted) {
            allCompleted = false;
            break;
          }
        }
        let _errs = null;
        let _items = [];
        
        if (allCompleted) {
          for (let i = 0; i < keys.length; i++) {
            let key = keys[i];
            if (stepCount[key].errors) {
              if (!_errs) {
                _errs = [];
              }
              _errs = _errs.concat(stepCount[key].errors);
            }
            
            _items = _items.concat(stepCount[key].items);
          }
          completedCallback(_errs, _items);
        }
        
      }
    }
    
    if (path === "_FILES") {
      if (PreloadConfig.files.length) {
        cc.loader.loadResArray(PreloadConfig.files, onProgress, onCompleted);
      }
      
    } else {
      cc.loader.loadResDir(path, onProgress, onCompleted);
    }
  }
  
  if (PreloadConfig.files.length) {
    preloadStep("_FILES");
  }
  for (let i = 0; i < PreloadConfig.directories.length; i++) {
    let dir = PreloadConfig.directories[i];
    preloadStep(dir);
  }
  
}

module.exports = {
  preload
};